package org.jdns.jfreechess.server;

import java.util.Map;
import java.util.Set;

import javax.inject.Inject;

import com.google.common.base.Function;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Ordering;
import com.google.common.collect.Sets;
import com.google.inject.Provider;

public class UserLocator {

  private final Provider<Map<String, User>> userProvider;

  @Inject
  public UserLocator(@ConnectedPlayers Provider<Map<String, User>> userProvider) {
    this.userProvider = userProvider;
  }

  public User getUserByName(String userName) {
    return userProvider.get().get(userName.toLowerCase());
  }

  public Set<User> findUsersByName(String userName) {
    Map<String, User> currentUsers = userProvider.get();
    User exactMatch = getUserByName(userName);
    if (exactMatch != null) {
      return ImmutableSet.of(exactMatch);
    }

    Set<User> result = Sets.newTreeSet(Ordering.natural().onResultOf(new Function<User, String>() {
      public String apply(User input) {
        return input.getName().toLowerCase();
      }
    }));

    String searchString = userName.toLowerCase();

    // otherwise, let's go hunting
    for (String key : currentUsers.keySet()) {
      if (key.startsWith(searchString)) {
        result.add(currentUsers.get(key));
      }
    }

    return result;
  }
}
